import React, { Component } from "react";
import { connect } from "react-redux";
import {
  messages,
  deepFullCopy,
  queryCurrencyPrecision,
  eventTrack,
} from "share/common";
import { Table, Icon, Spin, Row, Col, Input, Checkbox } from "antd";
import moment from "moment";
import baseService from "share/base.service";
import errorMessage from "share/errorMessage";
import Condition from "components/condition";
import ImageTrigger from "components/image-trigger";
import CreateInvoice from "containers/my-account/create-invoice-finance";
import dataSources from "containers/my-account/data-sources/data-sources";
import auditService from "../finance-audit.service";
import expenseService from "containers/my-account/expense.service";
import {
  auditSaveReceipt,
  shouldChangeFeeAutomatic,
} from "containers/my-account/components/common-method";
import rightNotSelectImg from "images/financial-management/audit/right-not-select.svg";
import leftNotSelectImg from "images/financial-management/audit/left-not-select.svg";
import rightSelectImg from "images/financial-management/audit/right-select.svg";
import leftSelectImg from "images/financial-management/audit/left-select.svg";

const { If } = Condition;
const { showUserInfo, showInternalInfo } = dataSources;

class InvoiceToBeChecked extends Component {
  state = {
    visible: false,
    currencyList: [],
    invoiceList: deepFullCopy(this.props.list),
    selectedFinanceId: this.props.list[0]
      ? this.props.list[0].financeReceipt.id
      : "",
    checkingIdList: [], //正在核对的 财务发票 列表id
    checkFailedIdList: [], //核对失败的 财务发票 列表id
    counterList: [], //核对成功的发票倒计时
    idToFormValuesMap: {}, //发票id和表单值的映射关系
    invoiceTypes: [], //发票类型
    columns: [],
    checkboxKeys: [], //复选框选中的key
    loadingIdList: [], // 正在加载的发票id
    loadingFinishedIdList: [], // 结束加载的发票id
    waitToCheckIdList: [], //待核对的财务发票id
    invoiceShowItemList: deepFullCopy(this.props.list).map(() => ({
      financeReceipt: [],
      withReceipt: [],
    })), // 发票展示字段
  };

  componentDidMount() {
    if (window.addEventListener) {
      window.addEventListener("keyup", this.handleKeyUp);
    } else {
      window.attachEvent("onkeyup", this.handleKeyUp);
    }
    this.getCurrencyList();
    const { invoiceList } = this.state;
    if (invoiceList[0]) {
      this.props.onSelect(invoiceList[0]);
      this.setState({
        loadingIdList: [
          invoiceList[0].financeReceipt.id,
          invoiceList[0].withReceipt.id,
        ],
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    const {
      checkCounterList,
      toBeCheckedInfo: { notMatchedNum, toBeCheckedNum },
    } = nextProps;
    const { selectedFinanceId, invoiceList } = this.state;
    const { counterList } = this.state;
    if (nextProps.visible && !this.state.visible) {
      this.setState(
        {
          visible: nextProps.visible,
          invoiceList: deepFullCopy(nextProps.list),
          selectedFinanceId: nextProps.list[0]
            ? nextProps.list[0].financeReceipt.id
            : "",
          invoiceShowItemList: deepFullCopy(nextProps.list).map(() => ({
            financeReceipt: [],
            withReceipt: [],
          })),
        },
        () => {
          this.focusInput();
          const { invoiceList } = this.state;
          if (invoiceList[0]) {
            this.props.onSelect(invoiceList[0]);
            this.setState({
              loadingIdList: [
                invoiceList[0].financeReceipt.id,
                invoiceList[0].withReceipt.id,
              ],
            });
          }
        }
      );
    }
    console.log("receive props checkCounterList", checkCounterList);
    if (
      checkCounterList.length > 0 &&
      this.props.checkCounterList.length === 0
    ) {
      let num = toBeCheckedNum;
      checkCounterList.map((id) => {
        this.state.invoiceList.map((list, index) => {
          if (list.financeReceipt.id === id) {
            num--;
            this.checkSuccessCounter(id);
            // 核对的发票当前已选中
            if (id === selectedFinanceId) {
              const nextIndex = this.getNextReceiptIndex(index + 1, true);
              this.handleSelectReceipt(
                nextIndex ? invoiceList[nextIndex].financeReceipt.id : ""
              );
            }
          }
        });
      });
      this.setState({ counterList, checkboxKeys: [] });
      this.props.onCheckKeysChange([]);
      this.props.onCheckSuccess(notMatchedNum, num);
    }
  }

  componentWillUnmount() {
    if (window.addEventListener) {
      window.removeEventListener("keyup", this.handleKeyUp);
    } else {
      window.detachEvent("onkeyup", this.handleKeyUp);
    }
  }

  focusInput = () => {
    setTimeout(() => {
      this.input && this.input.focus();
    }, 100);
  };

  getCurrencyList = () => {
    const { user } = this.props;
    baseService
      .getAllCurrencyByLanguage("zh_cn", user.userOID, true, false)
      .then((res) => {
        this.setState({ currencyList: res.data || [] });
      })
      .finally(() => {
        this.setState({
          columns: [
            {
              title: messages("expense-14.key182") /*财务扫描发票*/,
              dataIndex: "financeReceipt",
              render: (value) => this.renderInvoice(value, true),
            },
            {
              title: messages("expense-14.key183") /*员工录入发票（需贴票）*/,
              dataIndex: "withReceipt",
              render: (value) => this.renderInvoice(value),
            },
          ],
        });
      });
  };

  //键盘事件
  handleKeyUp = (e) => {
    e.stopPropagation();
    const { visible } = this.props;
    const { selectedFinanceId, invoiceList } = this.state;
    let selectedIndex = 0,
      nextIndex = 0;
    invoiceList.map(
      (item, index) =>
        item.financeReceipt.id === selectedFinanceId && (selectedIndex = index)
    );
    if (visible) {
      switch (e.keyCode) {
        //回车 DOWN
        case 13:
        case 40:
          nextIndex = this.getNextReceiptIndex(selectedIndex + 1, true);
          this.handleSelectReceipt(
            nextIndex ? invoiceList[nextIndex].financeReceipt.id : ""
          );
          break;
        //UP
        case 38:
          if (selectedIndex > 0) {
            nextIndex = this.getNextReceiptIndex(selectedIndex - 1);
            (nextIndex || nextIndex === 0) &&
              this.handleSelectReceipt(
                invoiceList[nextIndex].financeReceipt.id
              );
          }
          break;
        //TAB
        case 9:
          let element = document.activeElement;
          while (
            element &&
            !(element.id && element.id.search("matchedInvoice") === 0)
          ) {
            element = element.parentNode;
          }
          if (element && element.id) {
            this.handleSelectReceipt(element.id.split("matchedInvoice")[1]);
          }
          break;
      }
    }
  };

  //获取下一张／上一张发票的index
  getNextReceiptIndex = (index, isNext) => {
    const { invoiceList, checkingIdList } = this.state;
    if (checkingIdList.length === 0 && invoiceList[index]) {
      return index;
    }
    if (isNext) {
      for (let i = index; i < invoiceList.length; i++) {
        if (!~checkingIdList.indexOf(invoiceList[i].financeReceipt.id)) {
          return i;
        }
      }
    } else {
      for (let i = index; i >= 0; i--) {
        if (!~checkingIdList.indexOf(invoiceList[i].financeReceipt.id)) {
          return i;
        }
      }
    }
    return false;
  };

  // 查验失败后设置
  setFailedState = (financeReceiptId) => {
    const { checkingIdList, checkFailedIdList } = this.state;
    checkingIdList.delete(financeReceiptId);
    checkFailedIdList.addIfNotExist(financeReceiptId);
    this.setState({ checkingIdList, checkFailedIdList });
  };

  //检查发票是否被更改
  checkIsChange = () => {
    const { invoiceList, selectedFinanceId } = this.state;
    const { checkingIdList, checkFailedIdList, idToFormValuesMap } = this.state;
    const selectedReceipt = invoiceList.filter(
      (item) => item.financeReceipt.id === selectedFinanceId
    )[0];
    const financeFormRef = `formRef${selectedReceipt.financeReceipt.id}`;
    const withFormRef = `formRef${selectedReceipt.withReceipt.id}`;
    if (!this[financeFormRef] || !this[withFormRef]) {
      return;
    }
    const financeFormValues = this[financeFormRef].props.form.getFieldsValue();
    const withFormValues = this[withFormRef].props.form.getFieldsValue();
    const financeNowReceipt = this[financeFormRef].handleSubmit();
    const withNowReceipt = this[withFormRef].handleSubmit();
    if (!financeNowReceipt || !withNowReceipt) {
      return;
    }
    const invoiceTypes = this[financeFormRef].state.invoiceTypes;
    this[withFormRef].state.invoiceTypes.map((item) =>
      invoiceTypes.addIfNotExistObj(item, "value")
    );
    this.setState({ invoiceTypes });
    let hasItemChange = false;
    Promise.all(
      ["financeReceipt", "withReceipt"].map((type) => {
        return new Promise((resolve, reject) => {
          const receipt = selectedReceipt[type];
          const formValues =
            type === "financeReceipt" ? financeFormValues : withFormValues;
          const nowReceipt =
            type === "financeReceipt" ? financeNowReceipt : withNowReceipt;
          let hasChange = false;
          if (!nowReceipt) {
            reject();
          }
          idToFormValuesMap[selectedReceipt[type].id] = formValues;
          this.setState({ idToFormValuesMap });
          Object.keys(formValues).map((key) => {
            const keyMap = {
              image: "slicingAttachmentOID",
              invoiceCode: "billingCode",
              invoiceNumber: "billingNo",
              invoiceDate: "billingTime",
              priceTaxAmount: "fee",
              taxAmount: "tax",
              nonVATinclusiveAmount: "feeWithoutTax",
              owner: "receiptOwner",
              personInfo: "showUserInfo",
              internal: "internalStaff",
              issuedReceipt: "agentTag",
            };
            const checkKey = keyMap[key] || key;
            if (
              (receipt[checkKey] ||
                nowReceipt[checkKey] ||
                receipt[checkKey] === 0 ||
                nowReceipt[checkKey] === 0) &&
              nowReceipt[checkKey] + "" !== receipt[checkKey] + ""
            ) {
              receipt[checkKey] = nowReceipt[checkKey];
              hasChange = true;
              hasItemChange = true;
            }
          });
          if (hasChange) {
            const financeReceiptId =
              type === "financeReceipt"
                ? receipt.id
                : selectedReceipt.financeReceipt.id;
            checkingIdList.addIfNotExist(financeReceiptId);
            this.setState({ checkingIdList });
            Promise.all([this.handleVerify(receipt, type)])
              .then((res) => {
                if (res[0] && res[0].id) {
                  resolve(res[0].id);
                } else {
                  reject(financeReceiptId);
                }
              })
              .catch((err) => {
                // 正常不会走到catch，加埋点看下报错信息
                eventTrack({
                  category: "人工核对发票报错信息",
                  action: err,
                });
                this.setFailedState(financeReceiptId);
              });
          } else {
            resolve(receipt.id);
          }
        });
      })
    )
      .then((res) => {
        if (hasItemChange && res && res[0] && res[1]) {
          this.handleCheck(res);
        }
      })
      .catch((failedReceiptId) => {
        this.setFailedState(failedReceiptId);
      });
  };

  handleSelectReceipt = (financeReceiptId) => {
    const { invoiceList, selectedFinanceId } = this.state;
    if (financeReceiptId !== selectedFinanceId) {
      this.checkIsChange();
      this.setState(
        {
          selectedFinanceId: financeReceiptId || selectedFinanceId,
        },
        () => {
          this.focusInput();
          let selectedReceipt = invoiceList.filter(
            (item) => item.financeReceipt.id === financeReceiptId
          )[0];
          financeReceiptId && this.props.onSelect(selectedReceipt);
        }
      );
    }
  };

  //发票查验
  handleVerify = (receipt) => {
    const { user, entityID, entityOID, entityType } = this.props;
    let type = receipt.invoiceOID
      ? "invoice"
      : entityType === 5001
      ? "bag"
      : "expense_report";
    let expenseReportOID = entityType === 5001 ? "" : entityOID;
    let isFinancialOperateType = true;
    let isInvoiceFromFinancialEntry = !!type && type !== "invoice";
    return expenseService
      .testInvoice(
        receipt,
        user.userOID,
        type,
        entityID,
        expenseReportOID,
        isFinancialOperateType,
        isInvoiceFromFinancialEntry
      )
      .then(async (res) => {
        return await this.checkSuggestFieldsValue(res.data.invoiceInfo);
      })
      .catch(() => {
        return false;
      });
  };

  // 检查系统建议的费用字段信息
  checkSuggestFieldsValue = (invoiceInfo) => {
    const params = {
      invoiceOID: invoiceInfo.invoiceOID,
      receipts: [invoiceInfo],
    };
    const onConfirm = async (reviewResult, autoCalculate, resolve, reject) => {
      const res = await auditSaveReceipt(
        Object.assign({}, params, {
          reviewResult,
          autoCalculate,
          resetReviewResult: false,
        }),
        () => resolve(invoiceInfo),
        this
      );
      if (!res) {
        reject();
      }
    };
    return new Promise((resolve, reject) => {
      shouldChangeFeeAutomatic({
        type: "EDIT",
        params,
        currentReceipt: invoiceInfo,
        validAuth: invoiceInfo.entityType === "invoice",
        onDefaultConfirm: () => resolve(this.handleSave(invoiceInfo)),
        onConfirm: (reviewResult, autoCalculate) =>
          onConfirm(reviewResult, autoCalculate, resolve, reject),
        onCancel: () => reject(),
      });
    });
  };

  //发票保存
  handleSave = (receipt) => {
    const { entityID, entityType } = this.props;
    let type = receipt.invoiceOID
      ? ""
      : entityType === 5001
      ? "bag"
      : "expense_report";
    receipt.updateCheckResult = false;
    return expenseService
      .financialAuditInvoice(receipt, type, entityID)
      .then((res) => {
        return res.data.rows;
      })
      .catch(() => {
        return false;
      });
  };

  handleCheck = (receiptIdList) => {
    console.log("handleCheck", receiptIdList);
    let {
      entityOID,
      entityType,
      toBeCheckedInfo: { notMatchedNum, toBeCheckedNum },
    } = this.props;
    let {
      checkingIdList,
      checkFailedIdList,
      invoiceList,
      loadingIdList,
      waitToCheckIdList,
    } = this.state;
    // 当前有发票正在核对
    if (loadingIdList.length > 0) {
      waitToCheckIdList.addIfNotExist(receiptIdList[0]);
      this.setState({ waitToCheckIdList });
      return;
    }
    this.setState({ loadingIdList: receiptIdList });
    let params = {
      receiptList: receiptIdList,
      type: "TO_BE_CHECKED",
      entityType,
      entityCode: entityOID,
    };
    auditService
      .manualCheck(params, entityType)
      .then((res) => {
        let financeReceiptId = res.data.toBeCheckedReceiptId.financeReceipt;
        let withReceiptId = res.data.toBeCheckedReceiptId.withReceipt;
        checkingIdList.delete(financeReceiptId);
        //核对失败
        console.log("manualCheck response", res.data);
        if (res.data.checkTag === "TO_BE_CHECKED") {
          !~checkFailedIdList.indexOf(financeReceiptId) &&
            checkFailedIdList.push(financeReceiptId);
          invoiceList.map((item, index) => {
            if (item.financeReceipt.id === financeReceiptId) {
              invoiceList[index].financeReceipt.notMatchedColumns =
                res.data.notMatchedColumns;
            }
            if (item.withReceipt.id === withReceiptId) {
              invoiceList[index].withReceipt.notMatchedColumns =
                res.data.notMatchedColumns;
            }
          });
        }
        //核对成功
        if (res.data.checkTag === "CHECKED") {
          toBeCheckedNum--;
          checkFailedIdList.delete(financeReceiptId);
          this.checkSuccessCounter(financeReceiptId);
          deepFullCopy(receiptIdList).map((id) => {
            this.handleFinishLoading(id);
          });
        }
        //发票代码／号码不匹配
        if (res.data.checkTag === "NOT_MATCHED") {
          toBeCheckedNum--;
          notMatchedNum += res.data.notMatchedNum;
          checkFailedIdList.delete(financeReceiptId);
          //免贴票
          if (res.data.containsInvoiceFree) {
            invoiceList.map((item, index) => {
              item.financeReceipt.id === financeReceiptId &&
                (invoiceList[index].financeReceipt.containsInvoiceFree = true);
            });
            this.checkSuccessCounter(financeReceiptId);
          } else {
            invoiceList.map((item, index) => {
              item.financeReceipt.id === financeReceiptId &&
                invoiceList.splice(index, 1);
            });
          }
        }
        this.props.onCheckSuccess(notMatchedNum, toBeCheckedNum);
        this.setState({ invoiceList, checkingIdList, checkFailedIdList });
      })
      .catch((err) => {
        errorMessage(err.response);
        this.setFailedState(receiptIdList[0]);
        receiptIdList.map((id) => this.handleFinishLoading(id));
      });
  };

  //核对成功的发票倒计时
  checkSuccessCounter = (receiptId) => {
    let { counterList, invoiceList } = this.state;
    counterList.push({ id: receiptId, counter: 2 });
    let interval = setInterval(() => {
      counterList.map((item) => item.id === receiptId && item.counter--);
      this.setState({ counterList });
      if (!counterList.filter((item) => item.id === receiptId)[0].counter) {
        clearInterval(interval);
        counterList.deleteObj({ id: receiptId }, "id");
        invoiceList.map((item, index) => {
          if (item.financeReceipt.id === receiptId) {
            index === invoiceList.length - 1 &&
              this.handleSelectReceipt(invoiceList[0].financeReceipt.id);
            invoiceList.splice(index, 1);
          }
        });
        this.setState({ counterList, invoiceList });
      }
    }, 1000);
  };

  renderInvoiceItem = (key, values, receipt) => {
    const { language } = this.props;
    const { invoiceTypes, currencyList } = this.state;
    let currencyCode =
      values.vatInvoiceCurrencyCode || receipt.vatInvoiceCurrencyCode;
    let value = values[key];
    let showValue = value;
    const keyNameMap = {
      invoiceTypeNo: messages("common.invoice.type") /*发票类型*/,
      invoiceCode: messages("expense-14.key172") /*发票代码*/,
      invoiceNumber: messages("expense-14.key173") /*发票号码*/,
      invoiceDate: messages("expense-14.key187") /*开票日期*/,
      taxRate: messages("expense-14.key188") /*税率*/,
      vatInvoiceCurrencyCode: messages("common.currency") /*币种*/,
      priceTaxAmount: messages("expense-14.key189") /*价税合计*/,
      nonDeductibleAmount: messages("expense-14.key190") /*不可抵扣*/,
      taxAmount: messages("expense-14.key191") /*税额合计*/,
      nonVATinclusiveAmount: `${messages("expense-14.key192") /*金额合计*/}（${
        messages("expense-14.key193") /*不含税*/
      }）`,
      checkCode: messages("expense-14.key194") /*校验码*/,
      owner: messages("expense-14.key195") /*归属人*/,
      showUserInfo: messages("expense-14.key196") /*人员信息*/,
      internalStaff: messages("expense-14.key197") /*是否内部员工发票*/,
    };
    switch (key) {
      case "invoiceTypeNo":
        showValue = value
          ? (invoiceTypes.filter((item) => item.value === value)[0] || {})
              .messageKey
          : "-";
        break;
      case "invoiceDate":
        showValue = value ? moment(value).format("YYYY-MM-DD") : "-";
        break;
      case "taxRate":
        showValue =
          value !== undefined && value !== null
            ? isNaN(value)
              ? value
              : `${value * 100}%`
            : "-";
        break;
      case "vatInvoiceCurrencyCode":
        if (language.code === "zh_cn" && value) {
          showValue = `${value} ${
            currencyList.filter((item) => item.currency === value)[0]
              .currencyName
          }`;
        }
        break;
      case "priceTaxAmount":
      case "nonDeductibleAmount":
      case "nonVATinclusiveAmount":
        showValue =
          value || value === 0
            ? Number(value).toFixed(queryCurrencyPrecision(currencyCode))
            : "-";
        break;
      case "taxAmount":
        showValue =
          value === null || value === ""
            ? "-"
            : !isNaN(value)
            ? value.toFixed(queryCurrencyPrecision(currencyCode))
            : value;
        break;
      case "showUserInfo":
        showValue = showUserInfo[value];
        break;
      case "internalStaff":
        showValue = showInternalInfo[value];
        break;
    }
    return keyNameMap[key] ? (
      <Row className="text-row">
        <Col span={8} className="text-col-title">
          {keyNameMap[key]}
        </Col>
        <Col span={15} offset={1} className="text-col-content">
          {showValue || "-"}
        </Col>
      </Row>
    ) : null;
  };

  /**
   * 字段覆盖
   * itemName: 覆盖的字段名
   * receiptId: 财务扫描发票id
   * isCoverRight: 是否向右覆盖（财务覆盖员工）
   * extraParams: 额外参数
   **/
  handleItemCover = (itemName, receiptId, isCoverRight, extraParams = {}) => {
    const { invoiceList } = this.state;
    const withReceipt = invoiceList.find(
      (item) => item.financeReceipt.id === receiptId
    ).withReceipt;
    const financeRef = this[`formRef${receiptId}`];
    const withRef = this[`formRef${withReceipt.id}`];
    const financeForm = financeRef.props.form;
    const withForm = withRef.props.form;
    const itemChangeMap = new Map([
      ["invoiceTypeNo", { service: "handleReceiptNoChange" }],
      ["taxRate", { service: "handleChangeTaxRate" }],
      [
        "vatInvoiceCurrencyCode",
        { service: "selectVatInvoiceCurrencyCodeChange" },
      ],
      [
        "priceTaxAmount",
        { service: "handleAmountLinkage", params: ["priceTaxAmount"] },
      ],
      [
        "nonDeductibleAmount",
        { service: "handleAmountLinkage", params: ["nonDeductibleAmount"] },
      ],
      ["taxAmount", { service: "handleChangeTaxAmount" }],
      [
        "nonVATinclusiveAmount",
        { service: "handleChangeNonVATinclusiveAmount" },
      ],
    ]);
    // 若字段不可编辑，则不可被覆盖
    if ((isCoverRight ? withRef : financeRef).checkInvoiceRender(itemName, 3)) {
      return;
    }
    let fieldValue = (isCoverRight ? financeForm : withForm).getFieldsValue()[
      itemName
    ];
    extraParams.receiptNo && (fieldValue = extraParams.receiptNo);
    if (
      (isCoverRight ? withForm : financeForm).getFieldsValue()[itemName] ===
      fieldValue
    ) {
      return;
    }
    (isCoverRight ? withForm : financeForm).setFieldsValue({
      [itemName]: fieldValue,
    });
    if (itemChangeMap.get(itemName)) {
      (isCoverRight ? withRef : financeRef)[
        itemChangeMap.get(itemName).service
      ](...(itemChangeMap.get(itemName).params || []), fieldValue);
    }
  };

  renderCoverIcon = (itemName, receiptId, isFinance) => {
    return isFinance ? (
      <div className="invoice-item-cover-container">
        <ImageTrigger
          defaultUrl={rightNotSelectImg}
          triggerUrl={rightSelectImg}
          className="invoice-item-cover-container-icon"
          onClick={() => this.handleItemCover(itemName, receiptId, true)}
        />
        <ImageTrigger
          defaultUrl={leftNotSelectImg}
          triggerUrl={leftSelectImg}
          className="invoice-item-cover-container-icon"
          onClick={() => this.handleItemCover(itemName, receiptId, false)}
        />
      </div>
    ) : null;
  };

  renderInvoice = (receipt, isFinance) => {
    const { entityOID, userOID } = this.props;
    const {
      currencyList,
      invoiceList,
      checkingIdList,
      counterList,
      idToFormValuesMap,
      selectedFinanceId,
    } = this.state;
    let showTextIds = deepFullCopy(checkingIdList);
    counterList.map((item) => showTextIds.push(item.id));
    invoiceList.map(
      (item) =>
        ~showTextIds.indexOf(item.financeReceipt.id) &&
        showTextIds.push(item.withReceipt.id)
    );
    if (~showTextIds.indexOf(receipt.id) && idToFormValuesMap[receipt.id]) {
      return (
        <div className="invoice-manual-check-left-content-checked-text">
          {Object.keys(idToFormValuesMap[receipt.id]).map((key) => {
            return this.renderInvoiceItem(
              key,
              idToFormValuesMap[receipt.id],
              receipt
            );
          })}
        </div>
      );
    }
    return (
      <div
        key={receipt.id}
        style={{
          position: "relative",
          width: "98%",
          float: isFinance ? "left" : "right",
        }}
      >
        {receipt.id === selectedFinanceId && (
          <Input
            style={{ opacity: 0, position: "absolute" }}
            ref={(input) => (this.input = input)}
          />
        )}
        <CreateInvoice
          pageFrom="auditCheck"
          receipt={receipt}
          receiptOperateScene={3}
          currencyList={currencyList}
          receiptList={[]}
          expenseReportOID={entityOID}
          ownerOID={isFinance ? userOID : receipt.ownerOID}
          wrappedComponentRef={(inst) => (this[`formRef${receipt.id}`] = inst)}
          isFinance={isFinance}
          renderCoverIcon={(itemName) =>
            this.renderCoverIcon(itemName, receipt.id, isFinance)
          }
          onLoadingFinished={this.handleFinishLoading}
          setReceiptNo={(value) =>
            this.handleItemCover(
              "invoiceTypeNo",
              isFinance
                ? receipt.id
                : invoiceList.find((item) => item.withReceipt.id === receipt.id)
                    .financeReceipt.id,
              isFinance,
              { receiptNo: value }
            )
          }
        />
      </div>
    );
  };

  renderFooter = () => {
    return (
      <div className="default-color-inverse-font">
        <Icon type="exclamation-circle-o" />{" "}
        {messages("expense-14.key198") /*核对失败，请重新核对*/}
      </div>
    );
  };

  renderCounter = (id) => {
    const { counterList, invoiceList } = this.state;
    let counter = (counterList.filter((item) => item.id === id)[0] || {})
      .counter;
    let containsInvoiceFree = invoiceList.filter(
      (item) => item.financeReceipt.id
    )[0].containsInvoiceFree;
    let checkTagName = containsInvoiceFree
      ? messages("common.invoice.free") /*免贴票*/
      : messages("expense-14.key17"); /*已核对*/
    return (
      <div className="invoice-manual-check-left-content-checked-success">
        <Icon type="check-circle" />
        <span className="check-success-title">
          {
            containsInvoiceFree
              ? messages("expense-14.key176") /*免贴票发票无需核对*/
              : messages("expense-14.key199") /*发票核对正确*/
          }
        </span>
        {
          messages("expense-14.key178", {
            arg1: counter,
            arg2: checkTagName,
          }) /*{arg1}S后移动至【{arg2}】分类中*/
        }
      </div>
    );
  };

  handleCheckboxChange = (e, list) => {
    let { checkboxKeys } = this.state;
    list.map((item) => {
      ["financeReceipt", "withReceipt"].map((key) => {
        if (e.target.checked) {
          if (!checkboxKeys.includes(item[key].id)) {
            checkboxKeys.push(item[key].id);
          }
        } else {
          checkboxKeys.delete(item[key].id);
        }
      });
    });
    this.setState({ checkboxKeys });
    console.log({ checkboxKeys });
    this.props.onCheckKeysChange(checkboxKeys);
  };

  // 发票结束加载状态
  handleFinishLoading = (receiptId) => {
    let {
      invoiceList,
      loadingIdList,
      loadingFinishedIdList,
      waitToCheckIdList,
    } = this.state;
    loadingIdList.delete(receiptId);
    loadingFinishedIdList.addIfNotExist(receiptId);
    if (loadingIdList.length === 0) {
      // 页面初始加载
      if (loadingFinishedIdList.length < invoiceList.length * 2) {
        invoiceList.map((item, index) => {
          if (
            [item.financeReceipt.id, item.withReceipt.id].includes(receiptId) &&
            index < invoiceList.length - 1
          ) {
            loadingIdList = [
              invoiceList[index + 1].financeReceipt.id,
              invoiceList[index + 1].withReceipt.id,
            ];
          }
        });
      } else if (waitToCheckIdList.length > 0) {
        // 核对发票后加载
        invoiceList.map((item) => {
          if (waitToCheckIdList[0] === item.financeReceipt.id) {
            this.handleCheck([item.financeReceipt.id, item.withReceipt.id]);
          }
        });
        waitToCheckIdList.delete(waitToCheckIdList[0]);
      }
    }
    this.setState({ loadingIdList, loadingFinishedIdList, waitToCheckIdList });
  };

  // 发票组是否开始加载
  getItemVisible = (item) => {
    console.log('getItemVisible', item)
    const { loadingIdList, loadingFinishedIdList } = this.state;
    let itemVisible = true;
    [item.financeReceipt.id, item.withReceipt.id].map((id) => {
      if (!loadingIdList.includes(id) && !loadingFinishedIdList.includes(id)) {
        itemVisible = false;
      }
    });
    return itemVisible;
  };

  render() {
    const {
      invoiceList,
      selectedFinanceId,
      checkFailedIdList,
      checkingIdList,
      counterList,
      columns,
      checkboxKeys,
    } = this.state;
    const listIsSelected = invoiceList.map((item) =>
      checkboxKeys.includes(item.financeReceipt.id)
    );
    return (
      <div className="invoice-manual-check-left-content-checked">
        <div className="invoice-manual-check-left-content-alert">
          <Icon type="info-circle-o" />
          {
            messages(
              "expense-14.key200"
            ) /*请核对财务/员工发票数据和图片是否一致*/
          }
        </div>
        <If value={invoiceList.length > 1}>
          <Row style={{ marginTop: 16 }}>
            <Col span={4} className="col-left-checkbox">
              <Checkbox
                checked={!listIsSelected.includes(false)}
                indeterminate={
                  listIsSelected.includes(true) &&
                  listIsSelected.includes(false)
                }
                onChange={(e) => this.handleCheckboxChange(e, invoiceList)}
              />
            </Col>
            <Col
              span={20}
              className="col-right-content"
              style={{ fontWeight: "bolder" }}
            >
              {messages("expense-14.key201") /*全选发票*/}
            </Col>
          </Row>
        </If>
        {invoiceList.length > 0 ? (
          invoiceList.map((item, index) => (
            <Row style={{ marginTop: index === 0 ? 16 : 24 }}>
              <Col span={4} className="col-left-checkbox">
                <Checkbox
                  checked={checkboxKeys.includes(item.financeReceipt.id)}
                  onChange={(e) => this.handleCheckboxChange(e, [item])}
                />
              </Col>
              <Col span={20} className="col-right-content">
                <div
                  className={
                    item.financeReceipt.id === selectedFinanceId
                      ? "item-selected"
                      : ""
                  }
                >
                  <div className="invoice-manual-check-left-content-checked-title">
                    {
                      messages("expense-14.key202", {
                        arg1: index + 1,
                      }) /*发票{arg1}*/
                    }
                    :&nbsp;
                    <If value={item.financeReceipt.billingCode}>
                      {messages("expense-14.key172") /*发票代码*/}{" "}
                      {item.financeReceipt.billingCode}&nbsp;
                    </If>
                    <If value={item.financeReceipt.billingNo}>
                      {messages("expense-14.key173") /*发票号码*/}{" "}
                      {item.financeReceipt.billingNo}
                    </If>
                  </div>
                  <If
                    value={counterList.some(
                      (counterItem) => item.financeReceipt.id === counterItem.id
                    )}
                  >
                    {this.renderCounter(item.financeReceipt.id)}
                  </If>
                  <Spin
                    spinning={!!~checkingIdList.indexOf(item.financeReceipt.id)}
                  >
                    <div
                      id={`matchedInvoice${item.financeReceipt.id}`}
                      onClick={() =>
                        this.handleSelectReceipt(item.financeReceipt.id)
                      }
                    >
                      <Table
                        loading={
                          columns.length === 0 || !this.getItemVisible(item)
                        }
                        columns={columns}
                        dataSource={this.getItemVisible(item) ? [item] : []}
                        footer={
                          !~checkFailedIdList.indexOf(item.financeReceipt.id)
                            ? null
                            : this.renderFooter
                        }
                        pagination={false}
                        size="small"
                        border
                      />
                    </div>
                  </Spin>
                </div>
              </Col>
            </Row>
          ))
        ) : (
          <Spin />
        )}
      </div>
    );
  }
}

InvoiceToBeChecked.propTypes = {
  visible: React.PropTypes.bool,
  entityID: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string,
  ]),
  entityOID: React.PropTypes.string,
  entityType: React.PropTypes.number,
  list: React.PropTypes.array,
  toBeCheckedInfo: React.PropTypes.object,
  onSelect: React.PropTypes.func,
  onCheckSuccess: React.PropTypes.func,
};

InvoiceToBeChecked.defaultProps = {};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    language: state.main.language,
  };
}

export default connect(mapStateToProps)(InvoiceToBeChecked);
